package cn.tannn.tgateway.web.handler;

import cn.tannn.tgateway.DefaultGatewayPluginChain;
import cn.tannn.tgateway.GatewayFilter;
import cn.tannn.tgateway.GatewayPlugin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebHandler;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * gateway web handler
 *
 * @author <a href="https://t.tannn.cn/">tan</a>
 * @date 2024/5/30 上午10:35
 */
@Component("gatewayWebHandler")
@Slf4j
public class GatewayWebHandler implements WebHandler {

    /**
     * filter 集合
     */
    @Autowired
    List<GatewayFilter> filters;

    /**
     * 插件集合
     */
    @Autowired
    List<GatewayPlugin> plugins;




    @Override
    public Mono<Void> handle(ServerWebExchange exchange) {

        log.debug(" ====> tan Gateway web handler ... ");

        if (plugins == null || plugins.isEmpty()) {
            String mock = """
                    {"result":"no plugin"}
                    """;
            return exchange.getResponse()
                    .writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(mock.getBytes())));
        }
        // 执行过滤
        for(GatewayFilter filter : filters) {
            filter.filter(exchange);
        }
        // 执行plugins
        return new DefaultGatewayPluginChain(plugins).handle(exchange);
    }
}
